package com.fyyg.common.util;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author hang.ouyang
 * @date 2016-04-10 11:58
 */
public class XmlUtil {

    public static  String map2Xml(HashMap<String, String> map) {
        StringBuilder xml = new StringBuilder();
        xml.append("<xml>");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            xml.append("<").append(entry.getKey()).append(">").append(toXmlEscapeCharacter(entry.getValue())).append("</").append(entry.getKey()).append(">");
        }
        xml.append("</xml>");
        return xml.toString();
    }

    public static HashMap<String, String> xml2Map(byte[] xml) {
        SAXReader saxReader = new SAXReader();
        Document document = null;
        HashMap<String, String> result = new HashMap<>();
        try {
            document = saxReader.read(new ByteArrayInputStream(xml));
            org.dom4j.Element root = document.getRootElement();
            for (Iterator<Element> ie = root.elementIterator(); ie.hasNext(); ) {
                org.dom4j.Element element =  ie.next();
                result.put(element.getName(), element.getData().toString());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * xml特殊字符转义
     * @param s
     * @return
     */
    private static final String toXmlEscapeCharacter(String s) {
        if (s == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer(s.length() + 20);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '<') {
                sb.append("&lt;");
            } else if (c == '>') {
                sb.append("&gt;");
            } else if (c == '&') {
                sb.append("&amp;");
            } else if (c == '"') {
                sb.append("&quot;");
            } else if (c == '\'') {
                sb.append("&#39;");
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
